/**
 * 日期工具类
 */


/**
 * 补零
 * @param {*} num 
 */
export function zeroize( num ) {
	return (String(num).length == 1 ? '0' : '') + num
}

export function formatDateyyyymmdd( date ) {
  if (!date) return '';
  var d = new Date(date.replace(/\-/g, '/')),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return [year, month, day].join('-');
}

/**
 * 把时间转换成最近日期
 * @param {date} date 日期
 */
export function toLatelyDate (date) {
	let oldDate
	if (!date) {
		return date
	}
	if (Number(date)) {
		oldDate = new Date(parseInt(date))
	} else {
		// 在ios上必须要用 YYYY/MM/DD 的格式
		date = date.replace(new RegExp(/-/gm) ,"/");		
		oldDate = new Date(date)
	}
	// 今天时间
	let nowDate = new Date()

	if (oldDate > nowDate) {
		return date
	}
		
	// 一天时间			sec   min  hour
	let dayTime = 1000 * 60 * 60  * 24

	// 相差毫秒数
	let nowTime = nowDate.getTime()
	let oldTime = oldDate.getTime()
	let differTime = nowTime - oldTime
	
	let Y = oldDate.getFullYear()
	let Mon = oldDate.getMonth() + 1	
	let D = oldDate.getDate()
	let W = oldDate.getDay()
	let H = oldDate.getHours()
	let Min = oldDate.getMinutes()
	let S = oldDate.getSeconds()

	let nowYear = nowDate.getFullYear()
	let nowDay = nowDate.getDate()
	
	// 时分秒
	let HMS = zeroize(H) + ':' + zeroize(Min) + ':' + zeroize(S)
	// 今天
	if ( differTime < dayTime && nowDay === D )  {	
		return HMS;
	}
		
	// 昨天
	else if (differTime < dayTime * 3 &&  (new Date(oldTime + dayTime).getDate()) === nowDay) {
		return '昨天 ' + HMS;
	}

	// 一个周
	else if (differTime < dayTime * 7 ) {
		let weekList = ['日', '一', '二', '三', '四', '五', '六']
		return '星期' + weekList[W] + ' ' + HMS
	}	
	
	// 月 日 _ HMS
	// let MD_HMS = zeroize(Mon) + '/' + zeroize(D) + ' ' + HMS
	// 小于一年
	else if ( nowYear - Y <  1 ) {
		return zeroize(Mon) + '/' + zeroize(D) + ' ' + HMS
	} else { 	// 大于一年
		return Y + '/' + zeroize(Mon) + '/' + zeroize(D) + ' ' + HMS
	}
	
}


export function getDate(type, yearN) {
	const date = new Date();
	let year = date.getFullYear();
	if (yearN) {
		year = parseInt(year) + yearN
	}
	let month = date.getMonth() + 1;
	let day = date.getDate();

	if (type === 'start') {
		year = year - 60;
	} else if (type === 'end') {
		year = year
	}
	month = month > 9 ? month : '0' + month;;
	day = day > 9 ? day : '0' + day;
	return `${year}-${month}-${day}`;
}